package com.hou.zookeeper.zkclient;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.IZkStateListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;
import org.apache.zookeeper.Watcher;

public class ZkWatcher {
    /**
     * zookeeper地址
     */
    static final String CONNECT_ADDR = "192.168.171.128:2181,192.168.171.129:2181,192.168.171.130:2181";
    /**
     * session超时时间
     */
    static final int SESSION_OUTTIME = 5000;//ms

    public static void main(String[] args) throws InterruptedException {
        // 创建zkclient实例
        ZkClient zkClient = new ZkClient(new ZkConnection(CONNECT_ADDR, SESSION_OUTTIME), 10000);
        System.out.println("-----------");
        //监听子节点变化(不监听数据变化,只监听节点的新增删除)  IZkChildListener实现类
        zkClient.subscribeChildChanges("/father", (x, y) -> {//x:父路径, y:所有子节点路径集合
            System.out.println("parentPath: " + x);
            System.out.println("currentChilds: " + y);
        });
        Thread.sleep(2000);
        zkClient.createPersistent("/father");//父节点添加删除也会监听
        Thread.sleep(1000);
        zkClient.createPersistent("/father/son", "儿子");
        Thread.sleep(1000);
        zkClient.createPersistent("/father/daughter", "女儿");
        Thread.sleep(1000);
        zkClient.delete("/father/son");
        Thread.sleep(1000);
        zkClient.deleteRecursive("/father");
        //监听节点数据变化,监听之前节点必须存在,不监听子节点
        zkClient.createPersistent("/father", "1234");
        zkClient.subscribeDataChanges("/father", new IZkDataListener() {
            @Override   //节点数据变化
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println("变更的节点为:" + s + ", 变更内容为:" + o);
            }

            @Override  //节点删除
            public void handleDataDeleted(String s) throws Exception {
                System.out.println("删除的节点为:" + s);
            }
        });
        Thread.sleep(3000);
        zkClient.writeData("/father", "father");//-1:最新版本的数据
        Thread.sleep(1000);
        zkClient.delete("/father");//节点删除野人不监听
        Thread.sleep(1000);
        //监听服务连接状态,可手动启动关闭zookeeper查看触发
        zkClient.subscribeStateChanges(new IZkStateListener() {
            @Override
            public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception {
                if (state == Watcher.Event.KeeperState.SyncConnected) {
                    System.out.println("连接zookeeper成功");
                } else if (state == Watcher.Event.KeeperState.Disconnected) {
                    System.out.println("zookeeper断开");
                } else
                    System.out.println("other" + state);
            }

            @Override //连接关闭,过了session的设置时间,再连接session就会重置,触发监听
            public void handleNewSession() throws Exception {
                System.out.println("newsession");
            }
        });
        Thread.sleep(Integer.MAX_VALUE);//用不关闭线程,一直监听

    }
}
